using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace WindowsApplication1
{
    static class Server
    {
        static public Thread serverThread = new Thread(listen);
        static Socket socket;
        static Socket client;
        static IPEndPoint endpoint;
        static IPEndPoint clientep;

        public static void listen() {
            int recv;
            byte[] data = new byte[1024];
            try {
                endpoint = new IPEndPoint(IPAddress.Any,5008);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(endpoint);
                socket.Listen(4);
                Form1.updateListBox( "Socket successfully started and waiting for connections from Net Trust on port " + endpoint.Port + "." );
                client = socket.Accept();
                clientep = (IPEndPoint)client.RemoteEndPoint;
                Form1.updateListBox( "Net Trust connected from  " + clientep.Address + ":" + clientep.Port + "." );
                while (true)
                {
                    data = new byte[1024];
                    recv = client.Receive(data);
                    if (recv == 0)
                        break;
                    Program.send( Encoding.ASCII.GetString(data, 0, recv) );
                }
             }
            catch (SocketException e) {
                Form1.updateListBox( "Exception in listen(): " + e );
            }

        }
        public static int sendToScreen(string toSend)
        {
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(toSend);
            try
            {
                if (client != null)
                {
                    client.Send(data, data.Length, SocketFlags.None);
                    client.Send(Encoding.ASCII.GetBytes("\n"), 1, SocketFlags.None);
                }
                return (0);
            }
            catch (SocketException e)
            {
                Form1.updateListBox("Exception in sendToScreen(): " + e);
                return (-1);
            }
        }
    }
    static class Program
    {
        static SerialPort sp;
        static string pong;
        static public string[] ports = new string[32];

        public static int discoverComPort()
        {
            ports = scanPorts();
            int i = 0;
            foreach (string comPort in ports)
            {
                int tries = 0;
                sp = new SerialPort();
                if (comPort == null)
                    break;
                sp.PortName = comPort;
                sp.ReadTimeout = 300;
                sp.WriteTimeout = 300;
                try
                {
                    sp.Open();
                }
                catch (System.Exception ex)
                {
                    Form1.updateListBox("Exception while opening serial port: " + ex);
                }
            tryPort:
                try
                {
                    sp.Write("p");
                    pong = sp.ReadLine();
                    if (pong[0] == 'o')
                    {
 //                       sp.Close();
                        Thread readThread = new Thread(read);
                        readThread.Start();
                        Server.serverThread.Start();
                        return (i);
                    }
                }

                catch (TimeoutException)
                {
                    if (tries < 15)
                    {
                        tries++;
                        goto tryPort;
                    }
                    else
                        continue;
                }
                i++;
               }
            sp.Close();
            return (-1);
            
        }
        
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

        }

        public static void read()
        {
            tryRead:
                try
                {
                    string lineRead = sp.ReadLine();
                    Form1.updateListBox(lineRead);
                    Server.sendToScreen(lineRead);
                    goto tryRead;
                }
                catch (TimeoutException) { goto tryRead; }
        }
        public static int send( string toSend )
        {
            try
            {
                sp.Write(toSend);
                Form1.updateListBox("> " + toSend);
                return(0);
            }
            catch (TimeoutException) { return (-1); }
        }
        public static string[] scanPorts()
        {
            int i = 0;
            string[] ports = new string[32];

            foreach (string s in SerialPort.GetPortNames())
            {
                ports[i] = s;
                i++;
            }

            Console.WriteLine("  ");
            return ports;
        }
    }

}